﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Model
{
    [ObjectEvent]
    public class MessageDispatcherComponentEvent : ObjectEvent<MessageDispatcherComponent>, IAwake
    {
        public void Awake()
        {
            this.Get().Awake();
        }
    }


    public class MessageDispatcherComponent : Component
    {
        private Dictionary<Type, List<IMHandler>> handles;
        public void Awake()
        {
            this.Load();
        }

        /// <summary>
        /// 加载所有标记了MessageHandlerAttribute的类
        /// 再根据AppType，把实例，放到处理列表中去。
        /// </summary>
        public void Load()
        {
            AppType appType = Game.Scene.GetComponent<StartConfigComponent>().StartConfig.AppType;
            this.handles = new Dictionary<Type, List<IMHandler>>();
            List<Type> types = DllHelper.GetAllTypes();
            foreach (Type type in types)
            {
                object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute),false);
                if (attrs.Length == 0) continue;

                MessageHandlerAttribute attr = (MessageHandlerAttribute)attrs[0];
                if (!attr.Type.Is(appType)) continue;

                object obj = Activator.CreateInstance(type);

                IMHandler iMHandler = obj as IMHandler;
                if(iMHandler == null)
                {
                    throw new Exception($"消息处理没有继承IMHandle{obj.GetType().FullName}");
                }
                Type messageType = iMHandler.GetMessageType();
                if(!this.handles.TryGetValue(messageType, out List<IMHandler> list))
                {
                    list = new List<IMHandler>();
                    this.handles.Add(messageType, list);
                }

                list.Add(iMHandler);
            }
        }

        public void Handle(Session session,AMessage message)
        {
            if(!this.handles.TryGetValue(message.GetType(),out List<IMHandler> list))
            {
                Log.Error($"消息没有处理:{message.GetType().FullName}");
                return;
            }
            foreach (IMHandler item in list)
            {
                try
                {
                    item.Handle(session, message);
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                }
            }
        }
    }
}
